package com.ruoyi.web.controller.api;


import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ruoyi.cat.domain.AlipayConfig;
import com.ruoyi.cat.domain.CatTradedetailTable;
import com.ruoyi.cat.service.ICatBasedataTableService;
import com.ruoyi.cat.service.ICatTradedetailTableService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "api-文章管理相关")
@RestController
@RequestMapping("/api/alipayOracle")
public class AlipayPyController {

    @Value("${unionpay.pay-callback-host}")
    private String payCallbackHost;

    @Value("${unionpay.notify}")
    private String notify;

    @Value("${unionpay.returnCallback}")
    private String returnCallback;

    private static final String TRADE_SUCCESS = "TRADE_SUCCESS";
    private static final String TRADE_FINISHED = "TRADE_FINISHED";
    private static final String PAYMENT_TYPE_ALIPAY = "2";
    private static final String INITIAL_STATUS = "0";
    private static final String SUCCESS_STATUS = "1";

    @Autowired
    private ICatBasedataTableService catBasedataTableService;

    @Autowired
    private ICatTradedetailTableService catTradedetailTableService;


    @GetMapping("/returnCallback")
    public void returnCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Map<String, String> params = convertRequestToMap(request);
            log.info("支付宝同步回调，params：{}", params);

            if (verifyAlipaySign(params)) {
                String orderNo = params.get("out_trade_no");
                handleSuccessfulPayment(orderNo, params);
                CatTradedetailTable catTradedetailTable = catTradedetailTableService.selectCatTradedetailTableByOrderNo(orderNo);
                log.error("----------好的--------回调");
                response.sendRedirect("https://web.jiubeimao.com/article/editArticleTask?orderNo=" + orderNo+"&id="+catTradedetailTable.getActivityId());
            } else {
                log.error("支付宝同步回调签名认证失败");
                response.sendRedirect("http://你的域名/payment/fail");
            }
        } catch (Exception e) {
            log.error("支付宝同步回调处理异常", e);
            response.sendRedirect("http://你的域名/payment/fail");
        }
    }

    @PostMapping("/notify")
    public String notifyCallback(HttpServletRequest request) {
        try {
            Map<String, String> params = convertRequestToMap(request);
            log.info("支付宝异步回调，params：{}", params);

            if (verifyAlipaySign(params)) {
                String orderNo = params.get("out_trade_no");
                String tradeStatus = params.get("trade_status");

                if (isSuccessfulTradeStatus(tradeStatus)) {
                    updateOrderStatus(orderNo, params.get("trade_no"));
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("支付宝异步回调处理异常", e);
        }
        return "fail";
    }


    private boolean verifyAlipaySign(Map<String, String> params) throws AlipayApiException {
        AlipayConfig config = getAlipayConfig();
        return AlipaySignature.rsaCheckV1(
                params,
                config.getAlipayPublicKey(),
                config.getCharset(),
                config.getSignType()
        );
    }

    private void updateOrderStatus(String orderNo, String tradeNo) {
        CatTradedetailTable updateOrder = new CatTradedetailTable();
        updateOrder.setOrderNo(orderNo);
        updateOrder.setStatus(SUCCESS_STATUS);
        updateOrder.setTradeNo(tradeNo);
        catTradedetailTableService.updateCatTradedetailTableOrderNo(updateOrder);
    }

    private boolean isSuccessfulTradeStatus(String tradeStatus) {
        return TRADE_SUCCESS.equals(tradeStatus) || TRADE_FINISHED.equals(tradeStatus);
    }

    private void handleSuccessfulPayment(String orderNo, Map<String, String> params) {
        log.info("支付成功 - 订单号: {}, 支付宝交易号: {}, 支付金额: {}",
                orderNo,
                params.get("trade_no"),
                params.get("total_amount"));
    }

    private AlipayTradeQueryResponse queryAlipayTrade(AlipayClient alipayClient, String orderNo) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, String> bizContent = new HashMap<>();
        bizContent.put("out_trade_no", orderNo);
        request.setBizContent(new JSONObject(bizContent).toString());
        return alipayClient.execute(request);
    }

    private Map<String, String> createQueryResult(AlipayTradeQueryResponse response) {
        Map<String, String> result = new HashMap<>();
        result.put("tradeStatus", response.getTradeStatus());
        result.put("totalAmount", response.getTotalAmount());
        result.put("tradeNo", response.getTradeNo());
        return result;
    }

    private Map<String, String> convertRequestToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }
        return params;
    }


    private static AlipayConfig getAlipayConfig() {
        String privateKey  = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCtguyQX6fI/HhcNjYYq6XXNnvXVxI0jvLZkNPD/Fx+QDIF+qQz83CgMnMGNlYwKJ2bWJAgLH7RW93PjL7/luSOD2T8kXy7T209ALOV4TBRYTAHmaL45pzBOGefVydipS5fWbyX87n85XtfeTcwxKwgefKmXpg4vzdqeCdGbIVJQOzLLFQ3Gey+QP9vv7uE2tthVhf8WqGRcHRZqVJziY3aeRtZDhTbxWSyfwfD+7dMcVGWd9ulWNZ1/vaqmZmGgMJ4nvbwzLLVW2mMKbL7av6ptnB6n99Qu6qwBMN1f7ezBec2Nvcw85/5WgTEon1iEgBtSQsYz0TehPfqaUL0TBOvAgMBAAECggEBAJeQ5lS3Ojm3UOw77sVeK1/zl/pjdOO0ey7R9CofKCygpxHR/93hqWBGsXObw24ODJ7Gnh98vsrjFL9Ykv9xL/VoPS7jZ7G3kBTZqAYkz7BG1U3ORy5lREkEnH/0AdOJtxhTqwqRPMZNL5gWqr9PDYzQ+cWanB316tJ2YtiBs2xoehRm5DXQrpzCnX1gBnzVrZgY/UZE5VKUvMLQVV/496vaiViwIiZS9rNYcgTRiRdcd5UZaA5i+XJ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AZgAvP3YsNHLq5tWkV5W9tSYOVnsT6Ru1QOhJ7Bn9TWLlcV6f7knVQz4UJxvOFpK7Ps7QHvz9m0PYtse/b3ll/8eYhJHe6rRP3JKilqYsWTw4X8gAj8dr9xiLEsgqm1cKkM+cJH+m2qLEkBi3A6v5o5LoedjtwqoA4vhS4v6r+2f6V3LHyYpGeR7zHzaxs8aR57uBiuHes8acHTT9utpb90EtA/AmT+azGD4LOkjXI9warNv6CRANtj0bOf/+xSGFl3g1OG08GECLSFj2HNiFd1WVoYNQdUZlOG/mOBoQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId("2021005116671077");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

}
